package com.java.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author: wjr
 * @Description:
 * @Date Created in  2020-09-04 2:11
 * @Modified By:
 */

public class CommentFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String text = request.getParameter("text");
        //敏感词库
        String[] str = {"日本鬼子","韩国棒子","美国傻子","洋鬼子"};
        for (int i = 0; i < str.length; i++) {
            if (text.contains(str[i])){
                text = text.replaceAll(str[i], "****");
            }
        }

        //将过滤后的文本放入cookie中
        Cookie cookie = new Cookie("text", text);
        cookie.setMaxAge(60);//设置cookie的生命周期
        response.addCookie(cookie);

        //由后台给前台返回一段js代码
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.print("<script>alert('评论成功！已自动过滤敏感词');location.href='/comment.jsp'</script>");
    }

    @Override
    public void destroy() {

    }
}
